package com.xinghai.web.controller.api;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinghai.common.annotation.Log;
import com.xinghai.common.constant.CacheConstants;
import com.xinghai.common.core.controller.BaseController;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.core.redis.RedisCache;
import com.xinghai.common.enums.BusinessType;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.PageUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.common.utils.poi.ExcelUtil;
import com.xinghai.system.domain.QdChangeOrder;
import com.xinghai.system.domain.QdOrder;
import com.xinghai.system.domain.QdUser;
import com.xinghai.system.domain.entity.DataUpdateDTO;
import com.xinghai.system.domain.vo.QdStoreVo;
import com.xinghai.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 钱包api接口
 *
 * @author xinghai
 * @date 2024-12-04
 */
@RestController
@RequestMapping("/api/store/order")
public class QdStoreOrderApiController extends BaseController
{
    @Autowired
    private IQdUserService userService;
    @Autowired
    private IQdStoreService storeService;
    @Autowired
    private IQdOrderService orderService;
    @Autowired
    private IQdUserWalletService userWalletService;
    @Autowired
    private IQdChangeOrderService changeOrderService;
    @Autowired
    private RedisCache redisCache;



    /**
     * 查询卖出订单列表
     */
    @GetMapping("/getSellerOrderList")
    public AjaxResult getSellerOrderList(Integer pageNum,Integer pageSize,String type,String search,String status)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        PageUtils.startPage(pageNum,pageSize);
        PageUtils.orderBy("price desc");
        QdOrder order = new QdOrder();
        //order.setSellerUserId(Long.valueOf(loginId));
        order.setSellerStatus(type);
        order.setStoreId(user.getAscriptionStore());
        if (StringUtils.isBlank(status)){
            status = "0,1";
        }
        order.setStatus(status);
        order.setSearchValue(search);
        List<QdOrder> list = orderService.list(order);
        return success(getDataTable(list));
    }

    /**
     * 查询卖出订单列表
     */
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(String name)
    {
        QdUser user = new QdUser();
        user.setNickName(name);
        List<QdUser> list = userService.list(user);
        return success(list.isEmpty()?null:list.get(0));
    }




    /**
     * 指派买家
     */
    @PostMapping("/assignBuyer")
    public AjaxResult assignBuyer(@RequestBody DataUpdateDTO dto)
    {
        if (StringUtils.isBlank(dto.getIds())){
            return error("请选择至少一条记录");
        }
        if (StringUtils.isBlank(dto.getUserPhone())){
            return error("参数为空");
        }
        QdUser user = userService.getByUserPhone(dto.getUserPhone());
        if (user==null){
            return error("用户不存在");
        }
        QdStoreVo cacheMap = redisCache.getCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore());
        if (cacheMap==null){
            cacheMap = storeService.getIndexInfo(user.getAscriptionStore());
            redisCache.setCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore(), cacheMap);
        }
        if ((DateUtils.parseDate(cacheMap.getSaleStartDateDay()).compareTo(DateUtils.getNowDate())>-1
                ||DateUtils.parseDate(cacheMap.getSaleEndDateDay()).compareTo(DateUtils.getNowDate())<0)
                &&(DateUtils.parseDate(cacheMap.getReservationStartDateDay()).compareTo(DateUtils.getNowDate())>-1
                ||DateUtils.parseDate(cacheMap.getReservationEndDateDay()).compareTo(DateUtils.getNowDate())<0)){
            return error("指派单只能在预约、抢购时间内进行操作");
        }
        return success(orderService.assignBuyer(dto.getIds(),user.getId()));
    }


    /**
     * 更换卖家
     */
    @PostMapping("/changeSeller")
    public AjaxResult changeSeller(@RequestBody DataUpdateDTO dto)
    {
        if (StringUtils.isBlank(dto.getIds())){
            return error("请选择至少一条记录");
        }
        if (StringUtils.isBlank(dto.getUserPhone())){
            return error("参数为空");
        }
        QdUser user = userService.getByUserPhone(dto.getUserPhone());
        if (user==null){
            return error("用户不存在");
        }
        return success(orderService.changeSeller(dto.getIds(),user.getId()));
    }


    /**
     * 封存
     */
    @PostMapping("/closeOrder")
    public AjaxResult closeOrder(@RequestBody DataUpdateDTO dto)
    {
        if (StringUtils.isBlank(dto.getIds())){
            return error("请选择至少一条记录");
        }
        return success(orderService.closeOrder(dto.getIds()));
    }


    /**
     * 解开封存
     */
    @PostMapping("/openOrder")
    public AjaxResult openOrder(@RequestBody DataUpdateDTO dto)
    {
        if (StringUtils.isBlank(dto.getIds())){
            return error("请选择至少一条记录");
        }
        return success(orderService.openOrder(dto.getIds()));
    }

    /**
     * 转移订单
     */
    @PostMapping("/transferOrder")
    public AjaxResult transferOrder(@RequestBody DataUpdateDTO dto)
    {
        if (StringUtils.isBlank(dto.getIds())){
            return error("请选择至少一条记录");
        }
        if (StringUtils.isBlank(dto.getUserPhone())){
            return error("参数为空");
        }
        QdUser user = userService.getByUserPhone(dto.getUserPhone());
        if (user==null){
            return error("用户不存在");
        }
        if ("2".equals(dto.getType())&&!"2".equals(user.getUserType())){
            return error("只能选择店长进行转移");
        }
        return success(orderService.transferOrder(dto));
    }

    /**
     * 转移订单
     */
    @PostMapping("/transferOrderUpdate")
    public AjaxResult transferOrderUpdate(@RequestBody DataUpdateDTO dto)
    {
        if (StringUtils.isBlank(dto.getIds())){
            return error("请选择至少一条记录");
        }
        if (!"1".equals(dto.getStatus())&&!"2".equals(dto.getStatus())){
            return error("参数错误");
        }
        return success(orderService.transferOrderUpdate(dto));
    }

    /**
     * 合并
     */
    @PostMapping("/mergeOrder")
    public AjaxResult mergeOrder(@RequestBody DataUpdateDTO dto)
    {
        if (StringUtils.isBlank(dto.getIds())){
            return error("请选择至少一条记录");
        }
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        QdStoreVo cacheMap = redisCache.getCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore());
        if (cacheMap==null){
            cacheMap = storeService.getIndexInfo(user.getAscriptionStore());
            redisCache.setCacheObject(CacheConstants.STORE_INFO + user.getAscriptionStore(), cacheMap);
        }
        if (DateUtils.parseDate(cacheMap.getReservationEndDateDay()).compareTo(DateUtils.getNowDate())<0&&
                DateUtils.parseDate(cacheMap.getSaleEndDateDay()).compareTo(DateUtils.getNowDate())<0){
            dto.setNowStatus("1");
        }
        return success(orderService.mergeOrder(dto));
    }


    /**
     * 拆单
     */
    @PostMapping("/unpackOrder")
    public AjaxResult unpackOrder(@RequestBody DataUpdateDTO dto)
    {
        String loginId = StpUtil.getLoginId("");
        if (StringUtils.isBlank(dto.getIds())||StringUtils.isBlank(dto.getMoney())){
            return error("参数为空");
        }
        if (StringUtils.isBlank(dto.getStatus())&&StringUtils.isBlank(dto.getType())){
            return error("参数为空");
        }
        return success(orderService.unpackOrder(dto));
    }

    /**
     * 查询转移订单列表
     */
    @GetMapping("/getTransferOrderList")
    public AjaxResult getTransferOrderList(Integer pageNum,Integer pageSize,String type)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        PageUtils.startPage(pageNum,pageSize);
        PageUtils.orderBy("create_time desc");
        QdChangeOrder order = new QdChangeOrder();
        order.setStatus("0");
        order.setReceiveStatus("0");
        order.setNewStoreId(user.getAscriptionStore());
        if ("2".equals(type)){
            order.setType("2");
        }else if ("3".equals(type)){
            order.setType("3");
        }
        List<QdChangeOrder> list = changeOrderService.list(order);
        return success(getDataTable(list));
    }

    /**
     * 查询封存订单列表
     */
    @GetMapping("/getCloseOrderList")
    public AjaxResult getCloseOrderList(Integer pageNum,Integer pageSize,String search)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        PageUtils.startPage(pageNum,pageSize);
        PageUtils.orderBy("price desc");
        QdOrder order = new QdOrder();
        order.setStatus("1");
        order.setStoreId(user.getAscriptionStore());
        order.setSearchValue(search);
        List<QdOrder> list = orderService.list(order);
        return success(getDataTable(list));
    }
    /**
     * 查询买入订单列表
     */
    @GetMapping("/getBuyerOrderList")
    public AjaxResult getBuyerOrderList(Integer pageNum,Integer pageSize,String type,String search)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        PageUtils.startPage(pageNum,pageSize);
        PageUtils.orderBy("create_time desc");
        QdOrder order = new QdOrder();
        //order.setBuyerUserId(Long.valueOf(loginId));
        if ("0".equals(type)||"1".equals(type)){
            order.setBuyerStatusStr("0,1");
        }else {
            order.setBuyerStatus(type);
        }
        order.setStatus("0");
        order.setStoreId(user.getAscriptionStore());
        order.setSearchValue(search);
        List<QdOrder> list = orderService.list(order);
        return success(getDataTable(list));
    }

    /**
     * 生成对账单
     */
    @PostMapping("/genPayOrder")
    public AjaxResult genPayOrder()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        return success(orderService.genPayOrder(user.getAscriptionStore()));
    }


    /**
     * 生成对账单
     */
    @PostMapping("/payOrderDown")
    public AjaxResult payOrderDown()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        return success(orderService.genPayOrder(user.getAscriptionStore()));
    }

    /**
     * 一键确认平账
     */
    @PostMapping("/confirmOrder")
    public AjaxResult confirmOrder()
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        if (!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        return success(orderService.confirmOrder(user.getAscriptionStore()));
    }

    /**
     * 流拍
     */
    @PostMapping("/flow")
    public AjaxResult flow(@RequestBody DataUpdateDTO dto)
    {
        if (StringUtils.isBlank(dto.getIds())){
            return error("请选择至少一条记录");
        }
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        if (!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        return success(orderService.flow(dto.getIds(),user.getAscriptionStore()));
    }


    /**
     * 恢复待支付
     */
    @PostMapping("/toNoPay")
    public AjaxResult toNoPay(@RequestBody DataUpdateDTO dto)
    {
        if (StringUtils.isBlank(dto.getIds())){
            return error("请选择至少一条记录");
        }
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        if (!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        return success(orderService.toNoPay(dto.getIds(),user.getAscriptionStore()));
    }


    /**
     * 上架
     */
    @PostMapping("/listing")
    public AjaxResult listing(@RequestBody DataUpdateDTO dto)
    {
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        if (!"2".equals(user.getUserType())){
            return error("您不是店长，无法进行操作");
        }
        return success(orderService.listing(dto.getIds(),user.getAscriptionStore()));
    }


    /**
     * 审核
     */
    @PostMapping("/examine")
    public AjaxResult examine(@RequestBody DataUpdateDTO dto)
    {
//        if (StringUtils.isBlank(dto.getIds())){
//            return error("请选择至少一条记录");
//        }
        String loginId = StpUtil.getLoginId("");
        QdUser user = userService.getByLoginId(loginId);
        if (!"2".equals(user.getUserType())){
            return error("您不是店长，无法审核");
        }
        return success(orderService.examine(dto.getIds(),user.getAscriptionStore()));
    }

}
